//
//  NSMSearchHomeController.m
//  BSProject
//
//  Created by nsm on 2019/7/6.
//  Copyright © 2019 beisheng. All rights reserved.
//

#import "NSMSearchHomeController.h"

@interface NSMSearchHomeCell : NSMTableViewCell
@property (nonatomic, strong) UILabel *titleLabel;
@end

@implementation NSMSearchHomeCell
- (void)setObject:(id)obj {
    _titleLabel.text = SafeString(obj);
}

- (void)setupSubviews {
    self.backgroundColor = COLOR_4;
    self.contentView.backgroundColor = COLOR_4;
    
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Horz];
    layout.backgroundColor = COLOR_4;
    layout.wrapContentWidth = NO;
    layout.myHorzMargin = 0;
    layout.myHeight = 44;
    layout.cacheEstimatedRect = YES;
    layout.padding = UIEdgeInsetsMake(0, 15, 0, 0);
    layout.subviewHSpace = 12;
    layout.gravity = MyGravity_Vert_Center;
    [self.contentView addSubview:layout];
    self.rootLayout = layout;
    
    UIImageView *icon = [UIImageView new];
    icon.mySize = CGSizeMake(14, 14);
    icon.tintColor = SUB_TEXT_COLOR;
    icon.image = TemplateImage(@"nsm_search_history");
    [layout addSubview:icon];
    
    UILabel *label = [UILabel new];
    label.weight = 1;
    label.wrapContentHeight = YES;
    label.numberOfLines = 1;
    label.font = CustomFont(14);
    label.textColor = SUB_TEXT_COLOR;
    [layout addSubview:label];
    _titleLabel = label;
    
    NSMButton *deleteBtn = [NSMButton new];
    deleteBtn.mySize = CGSizeMake(44, 44);
    deleteBtn.imageSize = CGSizeMake(16, 16);
    deleteBtn.tintColor = SUB_TEXT_COLOR;
    deleteBtn.adjustsImageTintColorAutomatically = YES;
    [deleteBtn setImage:NameImage(@"nsm_search_delete") forState:UIControlStateNormal];
    [deleteBtn addTarget:self action:@selector(deleteHistory:) forControlEvents:UIControlEventTouchUpInside];
    [layout addSubview:deleteBtn];
}

- (void)deleteHistory:(id)sender {
    !self.actionBlock?:self.actionBlock(nil);
}

@end

@interface NSMSearchHomeController () <UITableViewDataSource>
@property (nonatomic, strong) MyFloatLayout *headerLayout;  //!< 展示热门推荐
@property (nonatomic, strong) MyLinearLayout *footerLayout; //!< 清除历史记录
@property (nonatomic, strong) NSArray *hotArray;            //!< 热门数据
@property (nonatomic, strong, readonly) NSArray *histories; //!< 历史记录数据
@end

@implementation NSMSearchHomeController
@synthesize didSelectSearchItem = _didSelectSearchItem;

#pragma mark - lifeCycle

#pragma mark - override
- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];
    
    self.tableView.height = self.view.height;
}

- (void)didInitialize {
    [super didInitialize];
    
    self.maximumHistories = 10;
}

#pragma mark - initialization
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.tableView.separatorInset = UIEdgeInsetsMake(0, 15, 0, 15);
    self.tableView.rowHeight = 44;
    self.tableView.dataSource = self;
    self.tableView.tableHeaderView = self.headerLayout;
    self.tableView.tableFooterView = self.footerLayout;
    self.tableView.keyboardDismissMode = UIScrollViewKeyboardDismissModeOnDrag;
    
    self.tableView.urlString = self.urlString;
    self.tableView.headerRefreshEnabled = self.urlString.length;
    
    @nsm_weak(self)
    self.tableView.didRefreshingHeaderSuccess = ^(id responseObject) {
        @nsm_strong(self)
        id data = ((NSMResponseObject *)responseObject).data;
        self.hotArray = SafeArray(data[@"hot_search"]);
        // 不让重复刷新头部,这种数据请求成功一次便可以了
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.25 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            self.tableView.headerRefreshEnabled = NO;
        });
    };

    if (self.urlString.length) {
        // 这里自由发挥加载方式
        [self.tableView beginRefreshing:RefreshHudNone];
    }
}

#pragma mark - UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    tableView.tableFooterView.hidden = !self.histories.count;
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.histories.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return self.histories.count?44:CGFLOAT_MIN;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (!self.histories.count) return nil;
    
    MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
    layout.backgroundColor = GROUP_TABLECOLOR;
    layout.myHorzMargin = 0;
    layout.myHeight = 44;
    layout.padding = UIEdgeInsetsMake(0, 15, 12, 15);
    layout.gravity = MyGravity_Vert_Bottom;
    layout.wrapContentHeight = NO;
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.wrapContentSize = YES;
    titleLabel.font = CustomFont(14);
    titleLabel.text = @"搜索历史";
    titleLabel.textColor = SUB_TEXT_COLOR;
    [layout addSubview:titleLabel];
    
    MyBorderline *line = [[MyBorderline alloc] initWithColor:SEPARATOR_COLOR];
    line.headIndent = 0;
    line.tailIndent = 0;
    layout.bottomBorderline = line;
    
    return layout;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    NSMSearchHomeCell *cell = [NSMSearchHomeCell cell:tableView];
    id item = self.histories[indexPath.row];
    [cell setObject:item];
    @nsm_weak(self)
    cell.actionBlock = ^(id obj) {
        @nsm_strong(self)
        [self deleteHistory:item];
    };
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    id item = self.histories[indexPath.row];
    !self.didSelectSearchItem?:self.didSelectSearchItem(item);
}

#pragma mark - NSMSearchHomeProtocol
- (void)insertLocal:(id)obj {
    [self updateSearchHistory:obj operate:NSMSearchOperateCreate];
}

#pragma mark - setter/getter
- (MyFloatLayout *)headerLayout {
    if (!_headerLayout) {
        MyFloatLayout *layout = [MyFloatLayout floatLayoutWithOrientation:MyOrientation_Vert];
        layout.myHorzMargin = 0;
        layout.wrapContentHeight = YES;
        layout.subviewHSpace = 12;
        layout.subviewVSpace = 8;
        _headerLayout = layout;
    }
    return _headerLayout;
}

- (MyLinearLayout *)footerLayout {
    if (!_footerLayout) {
        MyLinearLayout *layout = [MyLinearLayout linearLayoutWithOrientation:MyOrientation_Vert];
        layout.wrapContentHeight = NO;
        layout.myHorzMargin = 0;
        layout.myHeight = 64;
        layout.gravity = MyGravity_Center;
        [layout setTarget:self action:@selector(clearHistory)];
        
        UILabel *label = [UILabel new];
        label.wrapContentSize = YES;
        label.font = CustomFont(14);
        label.textColor = SUB_TEXT_COLOR;
        label.text = @"清空搜索历史";
        [layout addSubview:label];
        
        _footerLayout = layout;
    }
    return _footerLayout;
}

- (void)setHotArray:(NSArray *)hotArray {
    _hotArray = hotArray;
    
    [self.headerLayout removeAllSubviews];
    
    self.headerLayout.padding = UIEdgeInsetsMake(12, 15, 12, 15);
    
    UILabel *titleLabel = [UILabel new];
    titleLabel.weight = 1;
    titleLabel.myHeight = 24;
    titleLabel.font = CustomFont(14);
    titleLabel.text = @"热门搜索";
    titleLabel.textColor = SUB_TEXT_COLOR;
    [self.headerLayout addSubview:titleLabel];
    
    for (id item in hotArray) {
        NSMButton *btn  = [NSMButton new];
        btn.backgroundColor = THEME_LINE_COLOR;
        btn.myHeight = 27;
        btn.wrapContentWidth = YES;
        btn.contentEdgeInsets = UIEdgeInsetsMake(0, 15, 0, 15);
        btn.titleLabel.font = CustomFont(13);
        [btn setTitle:SafeString(item) forState:UIControlStateNormal];
        [btn setTitleColor:WhiteColor(1, 0.8) forState:UIControlStateNormal];
        [btn setTitleColor:WhiteColor(1, 0.8) forState:UIControlStateSelected];
        [btn addTarget:self action:@selector(searchHot:) forControlEvents:UIControlEventTouchUpInside];
        ViewCorner(btn, 3);
        [self.headerLayout addSubview:btn];
    }
    
    [self.headerLayout setNeedsLayout];
    [self.headerLayout layoutIfNeeded];
    self.tableView.tableHeaderView = self.headerLayout;
}

- (NSArray *)histories {
    return SafeArray([_cacheManager.searchCache objectForKey:self.historyCacheKey]);
}

#pragma mark - network

#pragma mark - method/public
- (void)updateSearchHistory:(id)obj operate:(NSMSearchOperate)operate {
    // 剔除无效key,防止数据污染
    if (!self.historyCacheKey.length) return;
    
    NSString *text = SafeString(obj);
    // 剔除无效数据
    if (!(text.length || operate==NSMSearchOperateClear)) return;

    NSMutableArray *cacheArray = @[].mutableCopy;
    NSArray *localArray = SafeArray([_cacheManager.searchCache objectForKey:self.historyCacheKey]);
    [cacheArray addObjectsFromArray:localArray];
    
    switch (operate) {
        case NSMSearchOperateCreate:
        {
            // 1.检查有没有重复的(交换下标还要考虑数据count==1,这种简单粗暴)
            BOOL isExist = [cacheArray containsObject:text];
            if (isExist) [cacheArray removeObject:text];
            [cacheArray insertObject:text atIndex:0];
            // 2.判断是否超出了容器范围
            if (cacheArray.count > self.maximumHistories) {
                [cacheArray removeLastObject];
            }
        }
            break;
        case NSMSearchOperateDelete:
            [cacheArray removeLastObject];
            break;
        case NSMSearchOperateClear:
            [cacheArray removeAllObjects];
            break;
        default:
            break;
    }
    
    // 保存,刷新
    [_cacheManager.searchCache setObject:cacheArray forKey:self.historyCacheKey withBlock:^{
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.tableView reloadData];
        });
    }];
}

#pragma mark - method/private

#pragma mark - action
- (void)searchHot:(NSMButton *)btn {
    !self.didSelectSearchItem?:self.didSelectSearchItem(btn.titleLabel.text);
}

- (void)deleteHistory:(id)obj {
    [self updateSearchHistory:obj operate:NSMSearchOperateDelete];
}

- (void)clearHistory {
    [self updateSearchHistory:@"" operate:NSMSearchOperateClear];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
}

@end
